class WriteDataBack
	attr_reader :content
	def initialize(sim_id)
		@content = <<OUTPUT
require 'mysql'
require 'find'

sim_id = %d
DB = Mysql.connect("localhost", "root", "rational", "exo_development")

data_files = []
bodies = {}

Find.find('data') do |path|
	if File.file?(path)
		data_files << File.basename(path)
	end
end

sim_bodies = DB.query("SELECT name, id FROM simulation_bodies WHERE simulation_id = #{sim_id}")
sim_bodies.each do |sim_body|
	bodies[sim_body[0].to_sym] = sim_body[1].to_i
end

sql_insert_string = "INSERT INTO simulation_data (simulation_body_id, time, semi_major_axis, eccentricity) VALUES "
rows = []

data_files.each do |data_file|
	name = data_file.gsub(/\.aei/,'')
	has_data = DB.query("SELECT simulation_body_id FROM simulation_data WHERE simulation_body_id = \#{bodies[name.to_sym]}")
	instances_of_body_data = 0

	has_data.each do |data|
		instances_of_body_data += 1
	end

	if instances_of_body_data == 0
		data = []
		file = File.open('data/' + data_file)
		file.each do |line|
			line.chomp!
			line = line.split(' ')
			data << line
		end
		data.slice!(0...4)
		data.each do |datum|
			rows << "(\#{bodies[name.to_sym]}, \#{datum[0]}, \#{datum[1]}, \#{datum[2]})"
		end
	end
end
DB.query(sql_insert_string + rows.join(','))
DB.close
OUTPUT
	@content = sprintf(@content,sim_id)
	end
end
